package org.anti996.ln_mybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.anti996.ln_mybatis.model.Account;
import org.anti996.ln_mybatis.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 账户表 前端控制器
 * </p>
 *
 * @author Anti996 Authors
 * @since 2022-07-11
 */
@Slf4j
@RestController
@RequestMapping(path = "/account", produces = "application/json")
@CrossOrigin(origins = "*")
public class AccountController {
    @Autowired
    private AccountServiceImpl accountService;

    @GetMapping
    public List<Account> accountList() {
        return accountService.list();
    }

    @GetMapping("/page/{no}")
    public List<Account> accountPage(@PathVariable(name = "no") int no) {
        Page<Account> page = accountService.page(new Page<>(no, 2));
        return page.getRecords();
    }

    @GetMapping("/{username}")
    public Account account(@PathVariable(name = "username") String username) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return accountService.getOne(wrapper);
    }

    @PostMapping(consumes = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public boolean insertAccount(@RequestBody Account account) {
        return accountService.save(account);
    }

    @PutMapping(path = "/{username}", consumes = "application/json")
    public boolean updateAccount(@PathVariable(name = "username") String username, @RequestBody Account account) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return accountService.update(account, wrapper);
    }

    @DeleteMapping("/{username}")
    public boolean deleteAccount(@PathVariable(name = "username") String username) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return accountService.remove(wrapper);
    }
}
